const axios = require('axios');
const fs = require('fs');
/**
 * @title 上传的文件名
 * @SPACE 上传空间的空间地址（对应的就是语雀空间打开的路径）
 * @REPOS 仓库地址（对应就是仓库打开的仓库路径）
 * @ID 文件（每个文件唯一的ID，可以通过F12在请求中查看）
 * @token 用户的token (可以在语雀的个人资料页面生成)
 */
const title = 'WebGIS配置文件';
const SPACE = 'small-space.yuque.com';
const REPOS = 'cabin/webgis_config';
const token = 'hIFWrCBztoN8aaFizGkrA9yq5j38w6AKMgqEUqte';
let ID = null;
/**
 * @tsUrl   接口文件路径
 * @jsonUrl 配置文件路径
 */
const tsUrl = '/src/interfaces/configs/';
const jsonUrl = '/docker/config/cfg/';

const readFiles = async () => {
  // 使用正则表达式匹配注释
  const RemarkReg = /\/\*[^]*?\*\//g;
  let markdown = '## 配置文件说明\n';
  const tsFiles = await fs.promises.readdir(__dirname.replace('scripts','') + tsUrl)
  let index = 0
  for(let tsfile of tsFiles){
    try {
      const tsData = await fs.promises.readFile(__dirname.replace('scripts','') + tsUrl + tsfile)
      const remarks = tsData.toString().match(RemarkReg)
      // 对注释进行过滤
      let filterRemarks = remarks.filter((remark) => remark.includes('title') && remark.includes('file'));
      const {title,file,desc,version} = getRemarks(filterRemarks);
      index += 1
      markdown += `### ${index}. ${file}(${title}) \n`;
      if(desc) {markdown += `<font color="#808080">${desc}</font> \n`;}
      markdown += '```TypeScript\n' + tsData + '\n``` \n';  
      // 判断是否携带版本号
      let cfgFile = '';
      if(!version){
        cfgFile = file + '.json5';
      }else{
        cfgFile = file + '@' + version + '.json5';
      }
      try{
        const jsonData = await fs.promises.readFile(__dirname.replace('scripts','') + jsonUrl + cfgFile)
        markdown += `配置文件: ${cfgFile} \n`;
        markdown += '```json\n' + jsonData + '\n``` \n';  
        markdown += '*** \n'
      }catch(err){
        markdown += `未找到对应配置文件！\n`
        console.log(`未找到配置文件${cfgFile}，请检查对应文件是否存在！`);
      }
    }catch(err){
      console.log(`扫描${tsfile}文件出现异常，请检查注释后再重新生成！`);
    }
  }
  return markdown
}

readFiles().then((markdown)=>{
  // 获取目录，判断是上传还是更新
  axios.get(`https://${SPACE}/api/v2/repos/${REPOS}`,{
    headers:{
      "X-Auth-Token": token,
    }
  }).then((response) => {
    // 解析目录，获取ID
    const {data} = response
    let lists = data.data.toc_yml
    let splitLists = lists.toString().split('- ')
    let newSplists = splitLists.map((splitList) => splitList.split('\n'))
    let docLists = newSplists.filter((newSplist) => newSplist.length === 14)
    docLists.forEach((docList) => {
      if(docList[1].includes(title)){
        // 匹配ID的正则表达式
        ID = docList[10].match(/\d+/)[0]
      }
    })
    if(!lists.toString().includes(ID)){
      // 首次上传 POST
      axios.post(`https://${SPACE}/api/v2/repos/${REPOS}/docs`,{
        title,
        body:markdown,
      },{
        headers:{
          "Content-Type":"application/json",
          "X-Auth-Token": token,
        }
      }).then(() => {
        console.log('WebGIS配置文件上传成功！');
      }).catch((err) => {
        console.log('WebGIS配置文件上传失败！',err);
      })
      return;
    }
    // 更新上传 PUT
    axios.put(`https://${SPACE}/api/v2/repos/${REPOS}/docs/${ID}`,{
      title,
      body:markdown,
    },{
      headers:{
        "Content-Type":"application/json",
        "X-Auth-Token": token,
      }
    }).then(() => {
      console.log('WebGIS配置文件更新成功！');
    }).catch((err) => {
      console.log('WebGIS配置文件更新失败！',err);
    })
  }).catch((err) => {
    console.log('目录请求失败！',err);
  })
})

// 解析注释
function getRemarks(filterRemarks){
  const remarks = filterRemarks[0].split('@')
  let title = '';
  let desc = '';
  let file = '';
  let version = '';
  // 过滤得到有用项
  const rightRemarks = remarks.filter((remark) => {
    return remark.includes('title') || remark.includes('desc') || remark.includes('version') || remark.includes('file')
  })
  const newRemarks = rightRemarks.map((rightRemark) => rightRemark.replace(/\r\n\s\D/g,""))
  for(let i = 0; i < newRemarks.length; i++){
    let str = newRemarks[i].split(' ')[0]
    let context = newRemarks[i].split(' ')[1]
    if(i === newRemarks.length - 1){
      context = context.split('/')[0]
    }
    switch(str){
      case 'title' : 
        title = context;
        break;
      case 'desc' : 
        desc = context;
        break;
      case 'file' :
        file = context;
        break;
      case 'version' : 
        version = context;
        break;
    }
  }
  return {title,file,desc,version}
}
